import strHtml from "./PasswordPage.html";
import { DomUtils } from "../../utils/DomUtils";
import { AccountService } from "../../services/AccountService";
import { BasePage } from "../BacePage";

export class PasswordPage extends BasePage {
  constructor() {
    super();
    document.body.classList.add(
      "bg-primary",
      "d-flex",
      "justify-content-center",
      "align-items-center",
      "min-vh-100",
      "p-5"
    );
  }

  render() {
    const dom = DomUtils.convertToDom(strHtml);
    this._bindEvents(dom);
    return dom;
  }

  _validateForm(dom) {
    const email = dom.querySelector("#emailaddress").value.trim();
    const password = dom.querySelector("#password").value.trim();

    if (!email) {
      alert("Email adderss is required.");
      return false;
    }
    if (!password || password.length < 8) {
      alert("Password must be at least 8 characters.");
      return false;
    }
    return true;
  }

  async _handleSubmit(event, dom) {
    event.preventDefault();
    if (!this._validateForm(dom)) return;

    const email = dom.querySelector("#emailaddress").value.trim();
    const password = dom.querySelector("#password").value.trim();

    const userData = {
      email,
      password,
    };

    try {
      const result = await AccountService.changePassword(userData);
      console.log("Password changed successfully", result);
      alert("Password changed successfully!");
      window.router.push("#/login");
    } catch (error) {
      console.error("Failed to change password", error);
      alert("Failed to change password. Please try again.");
    }
  }

  _bindEvents(dom) {
    const btn = dom.querySelector("#btnChangePassword");
    btn.addEventListener("click", (e) => this._handleSubmit(e, dom));
  }
}
